package com.kltn.zigo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
 
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.kltn.zigo.data.IP;
import com.kltn.zigo.process.JSONParser;
 
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class SearchResultActivity extends ListActivity {
	
	// Progress Dialog
    private ProgressDialog pDialog;
 
    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();
 
    ArrayList<HashMap<String, String>> placesList;
 
    // url to get all products list
    private static String url_all_place = IP.get_IP() + IP.get_path_service() +"get_all_place.php";
 
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PLACE = "place";
    private static final String TAG_PLACE_NAME = "place_name";
    private static final String TAG_ADDRESS = "address";
    private static final String TAG_COUNT_LIKE = "count_like";
 
    // products JSONArray
    JSONArray places = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search_result);
		
		placesList = new ArrayList<HashMap<String, String>>();		
		
		new LoadAllPlaces().execute();
		
		ListView lvPlace = getListView();
		
		lvPlace.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// getting values from selected ListItem
				String pid = ((TextView) view.findViewById(R.id.tvPlaceAddress)).getText()
						.toString();

				// Starting new intent
				Intent in = new Intent(getApplicationContext(),
						NewPostActivity.class);
				// sending pid to next activity
				in.putExtra(TAG_ADDRESS, pid);
				
				// starting new activity and expecting some response back
				startActivityForResult(in, 100);
			}
		});
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.search_result, menu);
		return true;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// if result code 100
		if (resultCode == 100) {
			// if result code 100 is received 
			// means user edited/deleted product
			// reload this screen again
			Intent intent = getIntent();
			finish();
			startActivity(intent);
		}
	}


	public class LoadAllPlaces  extends AsyncTask<String, String, String>{	    
	    @Override
	    protected void onPreExecute() {
	    	super.onPreExecute();
            pDialog = new ProgressDialog(SearchResultActivity.this);
            pDialog.setMessage("Loading places. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();	       
	    }

		@Override
		protected String doInBackground(String... args) {
	        // Building Parameters
	        List<NameValuePair> params = new ArrayList<NameValuePair>();
	        // getting JSON string from URL
	        JSONObject json = jParser.makeHttpRequest(url_all_place, "GET", params);

	        // Check your log cat for JSON reponse
	        Log.d("All Places: ", json.toString());

	        try {
	            // Checking for SUCCESS TAG
	            int success = json.getInt(TAG_SUCCESS);

	            if (success == 1) {
	                // products found
	                // Getting Array of Products
	                places = json.getJSONArray(TAG_PLACE);

	                // looping through All Products
	                for (int i = 0; i < places.length(); i++) {
	                    JSONObject c = places.getJSONObject(i);

	                    // Storing each json item in variable
	                    String placeName = c.getString(TAG_PLACE_NAME);
	                    String countLike = "Like: " + c.getString(TAG_COUNT_LIKE);
	                    String address = c.getString(TAG_ADDRESS);

	                    // creating new HashMap
	                    HashMap<String, String> map = new HashMap<String, String>();

	                    // adding each child node to HashMap key => value
	                    map.put(TAG_ADDRESS, address);
	                    map.put(TAG_PLACE_NAME, placeName);
	                    map.put(TAG_COUNT_LIKE, countLike);

	                    // adding HashList to ArrayList
	                    placesList.add(map);
	                }
	            } else {
	                // no products found
	                // Launch Add New product Activity
	                Intent i = new Intent(getApplicationContext(),
	                        NewPostActivity.class);
	                // Closing all previous activities
	                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	                startActivity(i);
	            }
	        } catch (JSONException e) {
	            e.printStackTrace();
	        }

	        return null;
	    }

	    //*//**
	    // * After completing background task Dismiss the progress dialog
	    // * **//*
	    protected void onPostExecute(String file_url) {
	        // dismiss the dialog after getting all products
	        pDialog.dismiss();
	        // updating UI from Background Thread
	        runOnUiThread(new Runnable() {
	            public void run() {
	               // *//**
	               //  * Updating parsed JSON data into ListView
	               //  * *//*
	                /*ListAdapter adapter = new SimpleAdapter(
	                        SearchResultActivity.this, placesList,
	                        R.layout.item_search_result, new String[] { TAG_PLACE_NAME,
	                                TAG_ADDRESS, TAG_COUNT_LIKE},
	                        new int[] { R.id.tvPlaceName, R.id.tvPlaceAddress, R.id.tvLikePlace });*/
	            	ListAdapter adapter = new SimpleAdapter(
	                        SearchResultActivity.this, placesList,
	                        R.layout.item_search_result, new String[] { TAG_PLACE_NAME,
	                                TAG_ADDRESS, TAG_COUNT_LIKE},
	                        new int[] { R.id.tvPlaceName, R.id.tvPlaceAddress, R.id.tvPlaceLike });
	                // updating listview
	                //lvPlace.setAdapter(adapter);     
	                setListAdapter(adapter);
	            	
	            }
	        });

	    }
	}
}

	

